package com.zwb.service.handlers;

import com.fasterxml.jackson.core.JsonParseException;
import com.zwb.service.enums.StatusCode;
import com.zwb.service.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author 头发又黑又长
 * @Date 2022/9/2 9:29
 * @email zwb15083976291@163.com
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {HttpMessageNotReadableException.class, JsonParseException.class, BindException.class})
    public R paramsExceptionHandler(Exception e) {
        log.error(e.getMessage());
        return R.result(StatusCode.VALID_ERROR);
    }

    @ExceptionHandler(value = {Exception.class})
    public R globalExceptionHandler(Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return R.result(StatusCode.SYSTEM_ERROR);
    }

    @ExceptionHandler(value = {SQLException.class})
    public R SqlexceptionHandler(SQLException e) {

        if (e instanceof SQLIntegrityConstraintViolationException) {
            return R.error("该数据存在相关联数据，操作失败！");
        }
        e.printStackTrace();
        log.error(e.getMessage());
        return R.error("数据库异常,操作失败");
    }
}
